#####################################################################
# File:         TextBox.py
# Product:      KnowledgeEngine.Components.TextBox
#
# Copyright:    Copyright (c) 2001, Faulkner Ltd.
# Author:       Brian Oliver
#
# Description:  This file defines the TextBox class, a simple
#               component to represent one or more lines of 
#               text entered during an assessment 
#
# See Also:     Component, Model, Section
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.KnowledgeEngineCore import *
from Products.KnowledgeEngine.Component import Component, ComponentInfo
from Products.KnowledgeEngine.Assessible import Assessible
from Products.KnowledgeEngine.KERLExtensions import KERLExtensions
from Products.KnowledgeEngine.Components.Section.Section import Section
from Products.KnowledgeEngine.Library.Library import Library
from Products.KnowledgeEngine.Report import *
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *
from Products.KnowledgeEngine.KERFProcessor import *

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## TextBoxInfo Class Definition
class TextBoxInfo(ComponentInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """

    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Return the class name
        """
        
        return 'TextBox'

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "TextBox"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "text"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('www/icon.gif', globals())

    #---------------------------------------------------------------#

    def isInstanceOf(self, className):
        """
            Returns if the class is an instance of the specified
            className, or implements the interface specified 
            by the className
        """

        return className == 'Assessible' or ComponentInfo.isInstanceOf(self, className)
    
    #---------------------------------------------------------------#
        
    def removeState(self, model):
        """
            Remove all component state for the specified model
            for this component type
        """

        #the delete query
        sql = "DELETE FROM texts WHERE modelid='%s'" % (model.getIdentity(),)

        #perform the query
        model.getDatabaseConnection().query(sql)
    
    #---------------------------------------------------------------#
        
    def deleteAssessment(self, model, identity):
        """
            Remove the assessment state for the specified model 
            and assessment identity
        """

        #the delete query
        sql = "DELETE FROM texts WHERE modelid='%s' AND assessmentid='%d'" % (model.getIdentity(), identity)

        #perform the query
        model.getDatabaseConnection().query(sql)
    
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ComponentInfo.onConfigureProperties(self)
        
        #add the 'reportContent' property        
        self.addPropertyDefinition(PropertyDefinition(identity="reportContent", displayName="Report Content", description="Text to be displayed for this component when used in a report", defaultValue="", propertyType=pt_STRING, propertyFormat=pf_HTML, propertyStructure=ps_ATOMIC))        
        
        #add the 'isMultiline' property        
        self.addPropertyDefinition(PropertyDefinition(identity="isMultiline", displayName="Multiline Content?", description="Is the assessment content to span multiple lines or remain on a single line?", defaultValue=false, propertyType=pt_BOOLEAN, propertyFormat=pf_SELECTION + pf_YES_NO, propertyStructure=ps_ATOMIC))        
        
        #add the 'defaultValue' property        
        self.addPropertyDefinition(PropertyDefinition(identity="defaultValue", displayName="Default Content", description="Initial text for new assessments", defaultValue="", propertyType=pt_STRING, propertyFormat=pf_TEXT_MULTILINE, propertyStructure=ps_ATOMIC))        

    #---------------------------------------------------------------#

#####################################################################
## TextBox Class Definition
class TextBox(Component, Assessible, KERLExtensions):
    """
        Defines a simple component to represent one or more lines of 
        text entered during an assessment.
    """

    #---------------------------------------------------------------#

    #TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = TextBoxInfo()
    
    #---------------------------------------------------------------#

    # DTML Methods
    index_html = DTMLFile('dtml/index_html', globals())
    simplereport_html = DTMLFile('dtml/simplereport_html', globals())

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the TextBox"        

        Component.__init__(self, id, identity)

    #---------------------------------------------------------------#

    def onAfterIdentityChange(self, identityMappings):
        """
            Handle Knowledge Engine specific actions after the 
            identity of this object has changed.
            
            The identityMappings dictionary holds 
            mappings from oldIdentities -> newIdentities
            (including this object)
                        
        """

        #perform default identity changes
        Component.onAfterIdentityChange(self, identityMappings)
                
    #---------------------------------------------------------------#
        
    def getIsMultiline(self):
        "Returns if the textbox is multiline"        
        return self.isMultiline
                
    #---------------------------------------------------------------#
        
    def getDefaultValue(self):
        "Returns the component assessment default value"        
        return self.defaultValue

    #---------------------------------------------------------------#

    def setDefaultValue(self, defaultValue):
        "Set the component assessment default value"        
        self.defaultValue = defaultValue
        
    #---------------------------------------------------------------#
        
    def hasDBState(self, model, assessmentIdentity, componentIdentity):
        """
            Return if the specified assessment identity is stored
            in the assessment database for this component.

            RETURN TYPE: Boolean
        """

        #create the sql query            
        sql = "SELECT value FROM texts WHERE cid='%s' and assessmentid='%s'" % (componentIdentity, assessmentIdentity)

        #perform the query
        (columns, resultset) = model.getDatabaseConnection().query(sql)

        #return if there is a result
        return len(resultset) > 0
        
    #---------------------------------------------------------------#
        
    def getDBState(self, model, assessmentIdentity, componentIdentity):
        """
            Return the state of the assessment identity from the
            database.

            RETURN TYPE: String
        """

        #create the sql query            
        sql = "SELECT value FROM texts WHERE cid='%s' and assessmentid='%s'" % (componentIdentity, assessmentIdentity)

        #perform the query
        (columns, resultset) = model.getDatabaseConnection().query(sql)

        #return the result
        if len(resultset) > 0:
            return resultset[0][0]
        else:
            return self.getDefaultValue()
        
    #---------------------------------------------------------------#
        
    def getState(self, model, assessmentIdentity, componentIdentity):
        """
            Return the state of the specified assessment identity
            for this component.
            
            RETURN TYPE: String
        """

        return self.getDBState(model, assessmentIdentity, componentIdentity)
        
    #---------------------------------------------------------------#
        
    def setDBState(self, model, assessmentIdentity, componentIdentity, value):
        """
            Set the state of the specified assessment identity
            to the specified value in the database for this component

            VALUE TYPE: String
        """

        #convert the value into an SQL friendly form
        value = toSQL(value)

        #is the component state already in the database?
        #(used to determine the type of query)
        if self.hasDBState(model, assessmentIdentity, componentIdentity):
            sql = "UPDATE texts SET value='%s' WHERE cid='%s' and assessmentid='%s'" % (value, componentIdentity, assessmentIdentity)
        else:
            sql = "INSERT INTO texts (cid, basecid, assessmentid, value, modelid) VALUES ('%s', '%s', '%s', '%s', '%s')" % (componentIdentity, self.getIdentity(), assessmentIdentity, value, model.getIdentity())

        #perform the query
        model.getDatabaseConnection().query(sql)
         
    #---------------------------------------------------------------#
        
    def setState(self, model, assessmentIdentity, componentIdentity, value):
        """
            Set the state of the specified assessment identity
            to the specified value for this component

            VALUE TYPE: String (possibly containing HTML markup)
        """

        self.setDBState(model, assessmentIdentity, componentIdentity, value)
    
    #---------------------------------------------------------------#
        
    def removeState(self, componentContext = None):
        """
            ABSTRACT: Remove the state of the component from all
            assessments given the provided context
        """

        #is the component in a library?
        if componentContext == None and self.isInLibrary():
            #the delete query for library components
            sql = "DELETE FROM texts WHERE basecid='%s'" % (self.getIdentity(),)        
            
        else:
            #the delete query for non-library components
            sql = "DELETE FROM texts WHERE cid='%s'" % (self.getIdentity(componentContext),)

        #perform the query
        self.getEnvironment().getDatabaseConnection().query(sql)

    #---------------------------------------------------------------#

    def toJavaScript(self, expression, componentContext = None):
        """
            Returns a Python string that represents a JavaScript
            expression, which may be used to evaluate the status
            of the component class specific KERL expression.

            NOTE: this method is primarily used to produce
            JavaScript expressions that form the basis of the
            client-side showif technology.
            
            RETURN TYPE: String         
        """
        
        #example: cond="['txt1','contains', value]" returns 'document.all("txt1:string").value.indexOf(value)>=0'
        #example: cond="['txt1','doesntcontain', value]" returns 'document.all("txt1:string").value.indexOf(value)<0'
        #example: cond="['txt1','equals', value]" returns 'document.all("txt1:string").value==value'
        #example: cond="['txt1','notequal', value]" returns 'document.all("txt1:string").value!=value'

        #get the identity (which is the identity of itself)        
        identity = self.getIdentity(componentContext)

        #get the operator
        opr = expression[1]

        #get the value
        value = asJavaScript(expression[2])

        #determine the result
        result = "document.all(\"" + identity + ":string\").value"
        
        if opr == "contains":
            return result + ".indexOf(\"" + value + "\")>=0"
        
        elif opr == "doesntcontain":
            return result + ".indexOf(\"" + value + "\")<0"
        
        elif opr == "equals":
            return result + "==\"" + value + "\""
        
        elif opr == "doesntequal":
            return result + "!=\"" + value + "\""
        
        else:
            return "true"

    #---------------------------------------------------------------#

    def evaluate(self, expression, assessmentCache, componentContext = None):
        """
            Evalutes the component class specific KERL expression
            using the provided assessmentCache.

            NOTE: this method is primarily used to produce
            JavaScript expressions that form the basis of the
            client-side showif technology.

            RETURN TYPE: Boolean         
        """
        
        #get the identity
        identity = self.getIdentity(componentContext)

        #get the operator
        opr = expression[1]

        #get the value
        value = asJavaScript(expression[2])

        #get the stored state
        state = assessmentCache.getState(identity)

        #evaluate the expression
        if opr == "contains":
            return state.find(value) >= 0
        
        elif opr == "doesntcontain":
            return state.find(value) == -1
        
        elif opr == "equals":
            return state == value
        
        elif opr == "doesntequal":
            return state != value
        
        else:
            return true
    
    #---------------------------------------------------------------#

    def updateKERLIdentities(self, expression, identityMappings):
        """
            Returns the expression with the appropriate old identities
            (as identified by the identityMappings) replaced with 
            new identities.
        """
        
        #get the component identity from the expression (first element)
        identity = expression[0]
        
        #is the component in the identityMappings?
        if identityMappings.has_key(identity):
            expression[0] = identityMappings[identity]
        
        return expression
        
    #---------------------------------------------------------------#

    def getComponentProperty(self, identity, propertyName, assessmentCache = None):
        """
            Returns the value of the specified property, given the
            identity of the component (which may be used to lookup states) and
            an assessment cache.

            RETURNS: None if the property doesn't exist
        """

        if propertyName == "value":
            return assessmentCache.getState(identity)
        else:
            return Component.getComponentProperty(self, identity, propertyName, assessmentCache)
        
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Component Information with the Knowledge Engine
registerGenericObjectClass(TextBox)

#####################################################################
